package com.zsx.shopping.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsx.shopping.common.api.user.dto.LoginDto;
import com.zsx.shopping.common.api.user.dto.RegisterDto;
import com.zsx.shopping.common.exception.ShoppingException;
import com.zsx.shopping.common.session.UserVO;
import com.zsx.shopping.user.converter.UserConverter;
import com.zsx.shopping.user.entity.User;
import com.zsx.shopping.user.enums.UserCodeMsg;
import com.zsx.shopping.user.service.UserService;
import com.zsx.shopping.user.mapper.UserMapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserConverter userConverter;

    @Override
    public Boolean exist(String username) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)) != null;
    }

    @Override
    public void register(RegisterDto registerDto) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, registerDto.getUsername()));
        if (user != null)
            throw new ShoppingException(UserCodeMsg.USERNAME_EXIST.getCode(), UserCodeMsg.USERNAME_EXIST.getMsg());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(registerDto.getPassword());
        user = new User();
        user.setUsername(registerDto.getUsername());
        user.setPassword(encodePassword);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        user.setNickname("新用户" + formatter.format(LocalDateTime.now()));
        userMapper.insert(user);
    }

    @Override
    public UserVO login(LoginDto loginDto) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginDto.getUsername()));
        if (user == null) {
            UserCodeMsg codeMsg = UserCodeMsg.USERNAME_PASSWORD_WRONG;
            throw new ShoppingException(codeMsg.getCode(), codeMsg.getMsg());
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(loginDto.getPassword(), user.getPassword())) {
            UserCodeMsg codeMsg = UserCodeMsg.USERNAME_PASSWORD_WRONG;
            throw new ShoppingException(codeMsg.getCode(), codeMsg.getMsg());
        }
        return userConverter.toUserInfo(user);
    }
}




